package com.app.service.impl;

import com.app.domain.bo.DanMuBo;
import com.app.domain.page.Page;
import com.app.domain.po.DanMuPo;
import com.app.domain.vo.DanMuVo;
import com.app.domain.vo.user.UserVo;
import com.app.framework.utils.CoBeanUtils;
import com.app.framework.utils.CollectionUtils;
import com.app.mapper.DanMuMapper;
import com.app.service.DanMuService;
import com.app.service.user.UserCommonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 弹幕方法实现
 */
@Service
public class DanMuServiceImpl extends ServiceImpl<DanMuMapper, DanMuPo> implements DanMuService {

    @Resource
    private UserCommonService userCommonService;

    /**
     * 弹幕列表
     *
     * @param articleId 文章ID
     */
    @Override
    @Cacheable(cacheNames = "danmu", key = "#articleId")
    public Page<DanMuVo> lists(Long articleId) {
        List<DanMuVo> danMuVos = baseMapper.lists(articleId);
        if (CollectionUtils.isEmpty(danMuVos)) {
            return Page.restPage(new ArrayList<>());
        }
        List<Long> userIds = new ArrayList<>();
        for (DanMuVo danMuVo : danMuVos) {
            userIds.add(danMuVo.getUserId());
        }
        Map<Long, UserVo> userMap = userCommonService.getUserMap(userIds);
        for (DanMuVo danMuVo : danMuVos) {
            danMuVo.setUser(userMap.get(danMuVo.getUserId()));
        }
        return Page.restPage(danMuVos);
    }

    /**
     * 添加弹幕
     *
     * @param bo 入参
     */
    @Override
    @CacheEvict(cacheNames = "danmu", key = "#bo.getArticleId")
    public void saveOne(DanMuBo bo) {
        DanMuPo danMuPo = CoBeanUtils.copy(bo, DanMuPo.class);
        danMuPo.setCreateTime(new Date());
        baseMapper.insert(danMuPo);
    }

    /**
     * 屏蔽弹幕
     *
     * @param danmuId 弹幕ID
     */
    @Override
    public void shield(Long danmuId) {
        DanMuPo danMuPo = baseMapper.selectById(danmuId);
        Assert.notNull(danMuPo, "评论弹幕不存在");
        danMuPo.setText("该弹幕已被管理员屏蔽");
        baseMapper.updateById(danMuPo);
    }

}